package com.common.util;

import cn.hutool.core.codec.Base64Decoder;
import cn.hutool.core.codec.Base64Encoder;
import cn.hutool.core.util.StrUtil;
import com.common.thread.TempFileDeleteThread;
import net.coobird.thumbnailator.Thumbnails;
import net.coobird.thumbnailator.geometry.Positions;
import org.apache.commons.fileupload.FileItem;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;


/**
 * 图片处理类
 * @author king
 *
 */
@Component
public class ImageUtil {


	public static String NGINXPATH = "D:/human-resources-system-demo/";
	public static String baidPath = "D:\\human-resources-system-demo\\SDK\\";
	public static String group = "prod";

	@Value("${file.upload.path}")
	public void setNginxPath(String path) {
		ImageUtil.NGINXPATH = path;
	}



	/**
	 * 将临时文件转移到正式的地址，临时的地址最多控制保存2天
	 *
	 * @param path
	 * @param savePath
	 * @return
	 */
	public static String saveFileRename(String path, String newPath, String savePath, String newFileName, String delPath) {
		new Thread(new TempFileDeleteThread(savePath+"/"+delPath)).start();// 删除2天前的临时文件
		String oldFileNanme = path.substring(path.lastIndexOf("/"));// 截取临时文件名称
		File temp = new File(savePath + "/" + path);// 获取临时文件
		if(StrUtil.isEmpty(newFileName)) {
			newFileName = oldFileNanme;
		}
		if (temp.exists()) {// 临时文件如果存在
			File report = new File(savePath + "/" + newPath);
			if (!report.exists()) {
				report.mkdirs();// 创建出文件夹
			}
			temp.renameTo(new File(savePath + "/"+newPath+"/" + newFileName));
			return newPath + newFileName;
		} else {// 不存在就去判断应存路径，如果存在，直接返回已存在路径
			if (new File(savePath + "/"+newPath+"/" + newFileName).exists()) {
				return newPath + newFileName;
			}
			return path;
		}
	}

	/**
	 * 图片转base64
	 * @param imgFile
	 * @return
	 */
	public static String getImageStr(String imgFile) {
		InputStream inputStream = null;
		byte[] data = null;
		try {
			inputStream = new FileInputStream(imgFile);
			data = new byte[inputStream.available()];
			inputStream.read(data);
			inputStream.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		String encode = Base64Encoder.encode(data);
		return encode;
	}


    /**
     * 存储base64图片
     *
     * @param imgStr
     * @param path
     * @return
     */
    public static boolean generateImage(String imgStr, String path) {
        if (imgStr == null)
            return false;
        try {
            File file = new File(path);
            if (!file.getParentFile().exists()) {// 先创建文件夹和文件
                file.getParentFile().mkdirs();
                file.createNewFile();
            }
			byte[] b = Base64Decoder.decode(imgStr);
            for (int i = 0; i < b.length; ++i) {
                if (b[i] < 0) {
                    b[i] += 256;
                }
            }
            OutputStream out = new FileOutputStream(path);
            out.write(b);
            out.flush();
            out.close();
            return true;
        } catch (Exception e) {
            return false;
        }
    }

	/**
	 * 处理上传的文件
	 * @param item
	 * @param filePath
	 * @param filenames
	 * @throws Exception
	 */
    public static boolean processUploadFile(FileItem item, String filePath, String filenames)  throws Exception  {
		// 此时的文件名包含了完整的路径，得注意加工一下
		String filename = item.getName();
		int index = filename.lastIndexOf("\\");
		filename = filename.substring(index + 1, filename.length());

		long fileSize = item.getSize();
		if ("".equals(filename) && fileSize == 0) {
			return false;
		}
		File file = new File(filePath+"/"+filenames);
		if (!file.getParentFile().exists()){
			file.getParentFile().mkdirs();
			file.createNewFile();
		}
		File uploadFile = new File(filePath + "/" + filenames);
		item.write(uploadFile);
		return true;
	}
    
    
    /**
     * 图片上传,并且自动压缩图片大小,图片大小超过100K自动按比例压缩到100K以下
     * @param item
     * @param filePath
     * @param filenames
     * @throws Exception
     */
    public static boolean processUploadFileGenerateSmall(FileItem item, String filePath, String filenames)  throws Exception  {
    	boolean rs = true;
    	// 此时的文件名包含了完整的路径，得注意加工一下  
        String filename = item.getName();         
        int index = filename.lastIndexOf("\\");  
        filename = filename.substring(index + 1, filename.length());  
 
        long fileSize = item.getSize();  
        if("".equals(filename) && fileSize == 0){             
        	return false;
        }  
        File file = new File(filePath+"/"+filenames);  
        if (!file.getParentFile().exists()){
            file.getParentFile().mkdirs();
            file.createNewFile();
        }
        File uploadFile = new File(filePath + "/" + filenames);  
        item.write(uploadFile);
        int kb = 100*1024;
        if(fileSize>100*1024){
        	int smallSize = (int) (fileSize%kb==0?fileSize/kb:fileSize/kb+1);
        	double size = Math.ceil(Math.sqrt(smallSize));
        	rs = ImageUtil.imageGenerateSmall(filePath + "/" + filenames, size);
        }
    	return rs;
    }
    
    /**
     * 图片上传,并且自动压缩添加水印
     * @param item
     * @param filePath
     * @param filenames
     * @throws Exception
     */
    public boolean processUploadFileByImage(FileItem item, String filePath,String filenames,int lastOid)  throws Exception  {  
    	// 此时的文件名包含了完整的路径，得注意加工一下  
    	String filename = item.getName();         
    	int index = filename.lastIndexOf("\\");  
    	filename = filename.substring(index + 1, filename.length());  
    	
    	long fileSize = item.getSize();  
    	if("".equals(filename) && fileSize == 0){             
    		return false;  
    	}  
    	File file = new File(filePath+"/"+lastOid);
    	if(!file.exists()){
    		file.mkdirs();
    	}
    	boolean rs = ImageUtil.imageSetSizeAndWatermark(400, 600, item.getInputStream(), filePath +"/"+lastOid+ "/" + filenames,filePath.replace("image","watermark")+"/"+lastOid+".png");
    	return rs;
    } 
    /**
     * 图片上传,并且自动压缩添加水印(整改照片)
     * @param item
     * @param filePath
     * @param filenames
     * @throws Exception
     */
    public boolean processUploadFileByImageUpdateImage(FileItem item, String filePath,String filenames,int lastOid)  throws Exception  {  
    	// 此时的文件名包含了完整的路径，得注意加工一下  
    	String filename = item.getName();         
    	int index = filename.lastIndexOf("\\");  
    	filename = filename.substring(index + 1, filename.length());  
    	
    	long fileSize = item.getSize();  
    	if("".equals(filename) && fileSize == 0){             
    		return false;  
    	}  
    	File file = new File(filePath+"/"+lastOid);
    	if(!file.exists()){
    		file.mkdirs();
    	}
    	boolean rs = ImageUtil.imageSetSizeAndWatermark(400, 600, item.getInputStream(), filePath +"/"+ filenames,filePath.replace("updateImage","watermark")+"/"+lastOid+".png");
    	return rs;
    }
	
	
	public static boolean imageSetSize(int height,int width,InputStream stream,String fileName){
		try {
			Thumbnails.of(stream).size(width, height).toFile(fileName);
		} catch (Exception e) {
			return false;
		}
		return true;
	}
	/**
	 * 缩放图片,并且加水印
	 * @param height
	 * @param width
	 * @param stream
	 * @param fileName
	 * @return
	 */
	public static boolean imageSetSizeAndWatermark(int width,int height,InputStream stream,String fileName,String watermarkName){
		try {
			File file = new File(watermarkName);
			if (file.exists()) {
				Thumbnails.of(stream)
				.size(width, height)
				.watermark(Positions.TOP_LEFT, ImageIO.read(file), 0.5f)
				.toFile(fileName);
			}else{
				Thumbnails.of(stream)
				.size(width, height)
				.toFile(fileName);
			}
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
		return true;
	}
	
	/**
	 * 生成缩略图
	 * @param path 文件完整的路径
	 * @param smallSize 文件压缩倍数
	 * @return
	 */
	public static boolean imageGenerateSmall(String path, double smallSize){
		try {
			File bigFile = new File(path);
			Image image = ImageIO.read(bigFile);
			int width = image.getWidth(null);
			int height = image.getHeight(null);
			int widthSmall = (int) (width / smallSize);
			int heightSmall = (int) (height / smallSize);
			BufferedImage buffi = new BufferedImage(widthSmall, heightSmall, BufferedImage.TYPE_INT_RGB);
			Graphics g = buffi.getGraphics();
			g.drawImage(image, 0, 0, widthSmall, heightSmall, null);
			g.dispose();
			ImageIO.write(buffi, "jpg", new File(path));
		} catch (IOException e) {
			e.printStackTrace();
			return false;
		}
		return true;
	}

	/**
	 * 删除存在文件
	 * @param path
	 * @return
	 */
	public static boolean deleteFile(String path){
		File file = new File(path);
		if(file.exists()){
			file.delete();
			return true;
		}else{
			return false;
		}
	}

	/*public static void main(String[] args) {
		try {
			long fileSize = 4030464;
			int kb = 100*1024;
	        if(fileSize>100*1024){
	        	int smallSize = (int) (fileSize%kb==0?fileSize/kb:fileSize/kb+1);
	        	double size = Math.ceil(Math.sqrt(smallSize));
	        	System.out.println(size);
	        	boolean result = imageGenerateSmall("F:\\桌面资料\\IMG\\SFZZM1.jpg",size);
	        	System.out.println(result);
	        }
		} catch (Exception e) {
			e.printStackTrace();
		}
	}*/
}
